package grammar;

import java.util.List;
import java.util.Vector;


public class Node {
	
	private Node leftChild;
	private Node rightChild;
	private String value;
	
	public Node(String value){
		this.value = value;
	}

	
	public static boolean insertNode(Node node, String value){

		if (!Operator.isOperator(node.value))
			return false;
	
		if (node.leftChild == null){
			Node newNode = new Node(value);
			node.leftChild = newNode;
			
		}
		
		else if (node.leftChild != null && node.rightChild != null){
			insertNode(node.rightChild, value);
		}
		
		else if (node.leftChild != null && node.leftChild.leftChild != null && node.leftChild.rightChild != null){
			node.rightChild = new Node(value);
		}
		
		else if (node.leftChild != null && Operator.isOperator(node.leftChild.value))
			insertNode(node.leftChild, value);

		else if (node.leftChild != null && !Operator.isOperator(node.leftChild.value)){
			node.rightChild = new Node(value); 
		}
		
		else
			return false;
		
		return true;
	
	}
	
	
	public static String printInOrder(Node node){

		String nodeString = "";
		String leftString = "";
		String rightString = "";
		
		
		if (node != null){
			
			leftString = leftString + printInOrder(node.leftChild);
			
			rightString = leftString + printInOrder(node.rightChild);
			
			if (Operator.isOperator(node.value))
				nodeString = nodeString + "(" + leftString + "" + node.value + "" + rightString + ")";
			
			else 
				nodeString = nodeString + node.value;
			
			System.out.println(nodeString);
		}
		
		return nodeString;

	}
	
	
	public static List<String> getPrerequisites(Node node){
		
		List<String> nodeList = new Vector<String>();
		List<String> leftList = new Vector<String>();
		List<String> rightList = new Vector<String>();
		
		if (node != null){
			
			leftList = getPrerequisites(node.leftChild);
			
			rightList = getPrerequisites(node.rightChild);
			
			if (node.value.equals(Operator.OR)){
				for (int i=0; i<leftList.size(); i++)
					nodeList.add(leftList.get(i));
				for (int i=0; i<rightList.size(); i++)
					nodeList.add(rightList.get(i));
			}
			
			else if (node.value.equals(Operator.AND)){
				
				for (int i=0; i<leftList.size(); i++){
					for (int j=0; j<rightList.size(); j++){
						nodeList.add(leftList.get(i) + " " + node.value + " " + rightList.get(j));
					}
				}

			}
			
			else
				nodeList.add(node.value);
			
		}
		return nodeList;

	}
	
}
